﻿using leapt.Common;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace leapt.Api.Middleware
{
    /// <summary>
    /// 业务需求。接口服务返回统一参数
    /// </summary>
    /// <remarks>
    /// {
    ///     "response":{
    ///         "code":200,
    ///         "message":"Remote service error",
    ///         "data":"",
    ///         "stuatus": true
    ///     }
    /// }
    /// </remarks>
    public class WebApiResultMiddleware: ActionFilterAttribute
    {
        //调用该方法会试状态码都变成200
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            //根据实际需求进行具体实现
            if (context.Result is ObjectResult)
            {
                var objectResult = context.Result as ObjectResult;
                if (objectResult.StatusCode == 200)  //成功
                {
                    context.Result = new ObjectResult(new ApiResponse(200, objectResult.Value, "", true));
                }
                else
                {
                    StringBuilder errinfo = new StringBuilder();
                    foreach (var s in context.ModelState.Values)
                    {
                        foreach (var p in s.Errors)
                        {
                            errinfo.AppendFormat("{0}", p.ErrorMessage);
                        }
                    }
                    context.Result = new ObjectResult(new ApiResponse(objectResult.StatusCode, "", errinfo.ToString(), false));
                }
            }
            else if (context.Result is EmptyResult)
            {
                context.Result = new ObjectResult(new ApiResponse(404, "", "未找到资源", false));
            }
            else if (context.Result is ContentResult)
            {
                context.Result = new ObjectResult(new ApiResponse(200, (context.Result as ContentResult).Content, "", true));
            }
            else if (context.Result is StatusCodeResult)
            {
                StringBuilder errinfo = new StringBuilder();
                foreach (var s in context.ModelState.Values)
                {
                    foreach (var p in s.Errors)
                    {
                        errinfo.AppendFormat("{0}", p.ErrorMessage);
                    }
                }
                bool status = (context.Result as StatusCodeResult).StatusCode == 200;
                context.Result = new ObjectResult(new ApiResponse((context.Result as StatusCodeResult).StatusCode, "", errinfo.ToString(), status));
            }
        }
    }
}
